<template>
	<view style="width: 100vw;">
		<view class="grid col-4 grid-square flex-sub">
			<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
				<image :src="imgList[index]" mode="aspectFill" :style="imgStyle"></image>
				<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
					<text class='cuIcon-close'></text>
				</view>
			</view>
			
			<button class="solids avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" v-if="isAvatar==true&&imgList.length<max">
				<text class='cuIcon-cameraadd'></text>
			</button> 
			
			<view class="solids" @tap="ChooseImage" v-if="isAvatar==false&&imgList.length<max">
				<text class='cuIcon-cameraadd'></text>
			</view>
			
		</view>
	</view>
</template>

<script>
	export default {
		name:"cu-upload",
		data() {
			return {
				imgList:[]
			};
		},
		props: {
			max: {
				type: Number,
				default: 1
			},
			isAvatar:{
				type:Boolean,
				default:false
			},
			imgStyle: {
				type: String,
				default: ''
			},
			imgs: {
				type: Array,
				default: []
			},
		},
		created() {
			this.imgList=this.imgs
			if(this.isAvatar){
				this.max=1
			}
		},
		methods:{
			// 选择图片
			ChooseImage() {
				uni.chooseImage({
					count: this.max, //可选图片，默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera','album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths.reverse())
						} else {
							this.imgList = res.tempFilePaths.reverse()
						}
						this.$emit("imgChange",this.imgList)
					}
				});
			},
			// 选择头像
			onChooseAvatar(e) {
			    const { avatarUrl } = e.detail 
			    this.imgList=[avatarUrl]
				this.$emit("imgChange",this.imgList)
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '删除提醒',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
							this.$emit("imgChange",this.imgList)
						}
					}
				})
			},
		}
	}
</script>

<style scoped>
.grid.col-4.grid-square>button.avatar-btn {
	display:inline-block;
	background-color:white;
	box-sizing: border-box;
    padding-bottom: calc((100% - 60rpx)/4);
    height: 0;
    width: calc((100% - 60rpx)/4);
	margin-left: 0rpx;
	margin-right: 20rpx;
	margin-bottom: 20rpx;
	border-radius: 6rpx;
	position: relative;
	left:0;
	overflow: hidden;
}
.avatar-btn .cuIcon-cameraadd{
	font-size: 52rpx;
	    position: absolute;
	    color: #8799a3;
	    margin: auto;
	    top: 0;
	    bottom: 0;
	    left: 0;
	    right: 0;
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    flex-direction: column;
}
</style>
